﻿using ConfExpert.Forms.Base;

using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Kauf
{
    public partial class TelaIhtiyaci : XForm
    {
        public TelaIhtiyaci()
        {
            InitializeComponent();
        }
        public TelaIhtiyaci(string Ids, int CustomerId, string SpName = "GetTelaIhtiyac",bool IsRequestable = true)
            : this()
        {
            this.Ids = Ids;
            this.CustomerId = CustomerId;
            this.SpName = SpName;

            btnOk.Enabled = IsRequestable;
        }

        BindingSource bsArticles, bsFoys, bsRolls;
        string Ids, SpName;
        //int count = 1;
        int CustomerId;
        private void OrtakKumas_Load(object sender, EventArgs e)
        {
            
            //gle.Properties.Assign(RI(Rp.Atelye)); 
            ds.Merge(Session.DataManager.ExecuteDataSet(SpName, Ids, CustomerId));

            DataRelation FK_TelaIhtiyaci = new DataRelation("FK_TelaIhtiyaci",
              ds.Tables["Table"].Columns["TelaId"],
              ds.Tables["Table1"].Columns["TelaId"]);
            ds.Relations.Add(FK_TelaIhtiyaci);

            DataRelation FK_Tela_rolls = new DataRelation("FK_Tela_rolls",
              ds.Tables["Table"].Columns["TelaId"],
              ds.Tables["Table2"].Columns["TelaId"]);
            ds.Relations.Add(FK_Tela_rolls);

            ds.Tables["Table2"].Columns.Add("KesilecekMiktar", typeof(decimal));
            ds.Tables["Table2"].Columns.Add("Seç", typeof(bool));
            ds.Tables["Table2"].Columns.Add("SelectedQty", typeof(decimal), "Iif(ISNULL(KesilecekMiktar,0)=0 and Seç=1, Qty, ISNULL(KesilecekMiktar,0))");
            ds.Tables["Table"].Columns.Add("AvailableQty", typeof(decimal), "Sum(Child(FK_Tela_rolls).Qty)");
            ds.Tables["Table"].Columns.Add("SelectedQty", typeof(decimal), "Sum(Child(FK_Tela_rolls).SelectedQty)");
            ds.Tables["Table"].Columns.Add("Fark", typeof(decimal), "SelectedQty-ToplamIhtiyac");



            bsArticles = new BindingSource(ds, "Table");
            bsFoys = new BindingSource(bsArticles, "FK_TelaIhtiyaci");
            bsRolls = new BindingSource(bsArticles, "FK_Tela_rolls");

            InitGridView(gvArticles, bsArticles);
            InitGridView(gvFoys, bsFoys);
            InitGridView(gvRolls, bsRolls);

            gvFoys.Columns["TelaId"].Visible = gvRolls.Columns["TelaId"].Visible = false;
            gvRolls.Columns["KesilecekMiktar"].VisibleIndex = gvRolls.Columns["Qty"].VisibleIndex + 1;

            gvArticles.FormatAsNumber(0, "ToplamIhtiyac", "SelectedQty", "Fark");
            gvArticles.FormatAsNumber(1, "AvailableQty");
            gvRolls.FormatAsNumber(0, "SelectedQty");

            gvArticles.AddSummary();
            gvRolls.AddSummary();

            gvFoys.BestFitColumns();

            gvFoys.AddSummary("Ihtiyac");

            gvFoys.OptionsView.EnableAppearanceEvenRow =
            gvFoys.OptionsView.EnableAppearanceOddRow =
                //gvArticles.OptionsView.EnableAppearanceOddRow =
                //gvArticles.OptionsView.EnableAppearanceEvenRow =
            gvRolls.OptionsView.EnableAppearanceOddRow =
            gvRolls.OptionsView.EnableAppearanceEvenRow = false;

            GridManager gm;
            gm = GridManager.GetManager(gvRolls);
            gm.GridMenu.AddMenu("Seç", AddRolls);
            gm.GridMenu.AddMenu("Bırak", RemoveRolls);


            gm = GridManager.GetManager(gvArticles);
            gm.GridMenu.AddMenu("Seç", AddRolls1);
            gm.GridMenu.AddMenu("Bırak", RemoveRolls1);
            gm.GridMenu.AddMenu("Uygun Topları Seç", SelectBySubsetSum);

            gvRolls.RowStyle += new RowStyleEventHandler(gvRolls_RowStyle);
            //gvArticles.RowStyle += new RowStyleEventHandler(gvArticles_RowStyle);
            gvArticles.RowCellStyle += gvArticles_RowCellStyle;
            btnOk.ItemClick += btnOk_ItemClick;
            //gvFoys.RowStyle += new RowStyleEventHandler(gvFoys_RowStyle); 
        }

        void btnOk_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DataRow[] drTop = ds.Tables["Table2"].Select("Seç=1 or KesilecekMiktar is not null");
            if (drTop.Length == 0)
            {
                ShowErrorMessage("Hiç top seçmediniz !");
                return;
            }

            DataRow[] drSelectedQty = ds.Tables["Table"].Select("Isnull(SelectedQty,0)>ToplamIhtiyac*1.1");
            if (drSelectedQty.Length > 0)
            {
                if (XtraMessageBox.Show("Toplam ihtiyacın %10 fazlasından daha fazla metrajda çıktığınız kumaşlar var. Devam etmek istiyor musunuz ?", "Uyarı", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                    return;
            }
            //string Atolye;
            ds.Tables["Table2"].Columns["SelectedQty"].Expression = string.Empty;
            ds.Tables["Table"].Columns["AvailableQty"].Expression = string.Empty;
            ds.Tables["Table"].Columns["SelectedQty"].Expression = string.Empty;

            int brandId = ds.Tables["Table3"].Rows[0]["BrandId"].ToInt();
            int sezonId = ds.Tables["Table3"].Rows[0]["SezonId"].ToInt();
            string dosyaNo = ds.Tables["Table3"].Rows[0]["DosyaNo"].ToString();
            int AtelyeId = 0;

            if (ds.Tables["Table4"].Rows.Count == 1)
                AtelyeId = ds.Tables["Table4"].Rows[0]["AtelyeId"].ToInt();

            using (CikisEmri ce = new CikisEmri("", "", ds.Tables["Table2"].Serialize(), Ids, brandId, sezonId, dosyaNo, CustomerId, true, "",AtelyeId))
                if (ce.ShowDialog() == DialogResult.OK)
                {
                    TelaCikisEmriId = ce.TelaCikisEmriId;
                    this.DialogResult = DialogResult.OK;
                }
        }

        void gvArticles_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {

                if (e.Column.FieldName == "SelectedQty")
                {
                    e.Appearance.Font = new Font(DevExpress.Utils.AppearanceObject.DefaultFont, FontStyle.Bold);
                }
                if (e.Column.FieldName == "Fark")
                {
                    if (gvArticles.GetRowCellValue(e.RowHandle, "Fark").ToInt() < 0)
                    {
                        e.Appearance.ForeColor = Color.Red;
                    }
                    else
                    {
                        e.Appearance.ForeColor = Color.Green;
                    }
                }
            }
        }



        void gvArticles_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "SelectedQty").ToDecimal() > 0)
                e.Appearance.BackColor = Color.LightBlue;
        }

        void gvRolls_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "SelectedQty").ToDecimal() > 0)
                e.Appearance.BackColor = Color.LightBlue;
        }

        void SelectBySubsetSum(object sender, EventArgs e)
        {
            int[] selectedRowIds = gvArticles.GetSelectedRows();
            List<int> selectedRollIds = new List<int>();

            foreach (int rowIndex in selectedRowIds)
            {
                int TelaId = (int)gvArticles.GetDataRow(rowIndex)["TelaId"];
                decimal target = Convert.ToDecimal(gvArticles.GetDataRow(rowIndex)["ToplamIhtiyac"]);

                DataRow[] drLines = ds.Tables["Table2"].Select("TelaId =" + TelaId);

                Dictionary<int, decimal> rolls = new Dictionary<int, decimal>();
                foreach (DataRow dr in drLines)
                {
                    int rollID = (int)dr["RollId"];
                    decimal qty = Convert.ToDecimal(dr["Qty"]);
                    rolls.Add(rollID, qty);
                }

                List<int> selectedRollId = SubsetSum.Select(target, rolls);
                selectedRollIds.AddRange(selectedRollId);
            }

            string strRollIds = string.Join(", ", Array.ConvertAll(selectedRollIds.ToArray(), i => i.ToString()));

            DataRow[] drSelectedRows = ds.Tables["Table2"].Select("RollId in (" + strRollIds + ")");
            foreach (DataRow dr in drSelectedRows)
            {
                dr["Seç"] = true;
            }

            Clipboard.SetText(strRollIds);
        }

        void AddRolls1(object sender, EventArgs e)
        {
            foreach (int handle in gvArticles.GetSelectedRows())
            {

                //gridView2.SetRowCellValue(handle, gridView2.Columns["Seç"], true);

                int TelaId = intParse(gvArticles.GetRowCellValue(handle, "TelaId"));
                foreach (DataRow r in ds.Tables["Table2"].Select("TelaId = " + TelaId.ToString()))
                    r["Seç"] = true;

            }

            gvArticles.RefreshData();
            gvRolls.RefreshData();
        }

        void RemoveRolls1(object sender, EventArgs e)
        {
            foreach (int handle in gvArticles.GetSelectedRows())
            {

                //gridView2.SetRowCellValue(handle, gridView2.Columns["Seç"], true);

                int TelaId = intParse(gvArticles.GetRowCellValue(handle, "TelaId"));
                foreach (DataRow r in ds.Tables["Table2"].Select("TelaId = " + TelaId.ToString()))
                    r["Seç"] = false;

            }

            gvArticles.RefreshData();
            gvRolls.RefreshData();
        }

        void RemoveRolls(object sender, EventArgs e)
        {
            foreach (int handle in gvRolls.GetSelectedRows())
                gvRolls.SetRowCellValue(handle, "Seç", false);
            gvArticles.RefreshData();
            gvRolls.RefreshData();
        }

        void AddRolls(object sender, EventArgs e)
        {
            foreach (int handle in gvRolls.GetSelectedRows())
                gvRolls.SetRowCellValue(handle, "Seç", true);
            gvArticles.RefreshData();
            gvRolls.RefreshData();
        }

        public int TelaCikisEmriId { get; set; }
    }
}
